const fs = require('fs');

function addMapping(router, mapping){
    for (var url in mapping){
        if(url.startsWith('GET ')){
            //如果url类似'GET xxx'
            //substing 提取字符串

            var path = url.substring(4);
            router.get(path,mapping[url]);
            console.log(`register URL mapping:GET ${path}`);
        } else if (url.startsWith('POST ')) {
            var path = url.substring(5);
            router.post(path,mapping[url]);
            console.log(`register URL mapping: POSR ${path}`);
        } else if (url.startsWith('PUT ')) {
            var path = url.substring(4);
            router.post(path,mapping[url]);
            console.log(`register URL mapping: PUT ${path}`);
        } else if (url.startsWith('DELETE ')) {
            var path = url.substring(7);
            router.post(path,mapping[url]);
            console.log(`register URL mapping: DELETE ${path}`);
        }  else {
            console.log(`invalid URL: ${url}`);
        }
    }
}

function addControllers(router,dir){
    fs.readdirSync(__dirname + '/' +dir).filter((f)=>{
        return f.endsWith('.js');
    }).forEach((f)=>{
        console.log(`process controllers: ${f}...`);
        let mapping = require(__dirname + '/' + dir + '/' + f);
        addMapping(router,mapping);
    });
}

module.exports = function(dir){
    let 
        controllers_dir = dir || 'controllers',
        router = require('koa-router')();
    addControllers(router,controllers_dir);
    return router.routes();
}


